package mk.company.fin.model;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

import mk.company.fin.FinConstants;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Index;

@Entity
@Table(name = FinConstants.Tables.KONTO_SYNTHETIC, 
		uniqueConstraints = {@UniqueConstraint(columnNames = {"value", "id_konto_group"})})
public class KontoSynthetic extends Model {

	private static final long serialVersionUID = -2911881094017253390L;

	// persistent
	private Long id;
	private String value;
	private String description;
	private KontoGroup kontoGroup;
	private List<Konto> kontos;
	
	// dynamic
	private String synthetic;
	
	
	@Id
	@Column(name = "id_konto_synthetic")
	@GeneratedValue//(strategy = GenerationType.SEQUENCE)
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}

	@Column(nullable = false, length = 1)
	@Index(name = FinConstants.Tables.KONTO_SYNTHETIC + "_search")
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		if (StringUtils.isNotEmpty(value) && value.length() == 1) {
			this.value = value;
		}
	}

	@Column
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name = "id_konto_group", nullable = false)
	@Index(name = FinConstants.Tables.KONTO_SYNTHETIC + "_search")
	public KontoGroup getKontoGroup() {
		return kontoGroup;
	}

	public void setKontoGroup(KontoGroup kontoGroup) {
		this.kontoGroup = kontoGroup;
	}
	
	@OneToMany(mappedBy = "kontoSynthetic", orphanRemoval = true, fetch = FetchType.LAZY)
	public List<Konto> getKontos() {
		return kontos;
	}

	public void setKontos(List<Konto> kontos) {
		this.kontos = kontos;
	}
	
	
	/**
	 * @return Class + Group + Synthetic from the Konto
	 */
	@Transient
	public String getSynthetic() {
		if (synthetic == null) {
			KontoGroup kontoGroup = getKontoGroup();
			if (kontoGroup != null) {
				synthetic = kontoGroup.getGroup() + getValue();
			} else {
				synthetic = "??" + getValue();
			}
		}
		return synthetic;
	}
	
	@Deprecated
	public void setSynthetic(String synthetic) {
		throw new UnsupportedOperationException("The field synthetic is dynamic!");
	}
	
	@Override
	public String toString() {
		return getSynthetic();
	}
	
}
